package com.yoomiito.app.base;

import static com.yoomiito.app.utils.ImageUtils.getTempFileName;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.GradientDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSONObject;
//import com.amap.api.location.AMapLocation;
//import com.amap.api.location.AMapLocationClient;
//import com.amap.api.location.AMapLocationClientOption;
//import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.scrat.app.selectorlibrary.ImageSelector;
import com.tbruyelle.rxpermissions2.Permission;
import com.umeng.message.PushAgent;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yoomiito.app.BuildConfig;
import com.yoomiito.app.Constant;
import com.yoomiito.app.MainActivity;
import com.yoomiito.app.R;
import com.yoomiito.app.model.ShareViewData;
import com.yoomiito.app.model.bean.BannerAndIconInfo;
import com.yoomiito.app.model.bean.GoodsDetail;
import com.yoomiito.app.net.NetUrl;
import com.yoomiito.app.pay.PayTypeUtils;
import com.yoomiito.app.present.WebViewPresenter;
import com.yoomiito.app.share.ui.NewInviteShareActivity;
import com.yoomiito.app.share.ui.ShareActivity;
import com.yoomiito.app.ui.my.MyUserInfoActivity;
import com.yoomiito.app.ui.order.list.OrderActivity;
import com.yoomiito.app.utils.ActTypeUtils;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.ColorUtils;
import com.yoomiito.app.utils.Const;
import com.yoomiito.app.utils.DeviceConfigUtils;
import com.yoomiito.app.utils.FileUtils;
import com.yoomiito.app.utils.ImageLoader;
import com.yoomiito.app.utils.ImageUtils;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.LoginUtils;
import com.yoomiito.app.utils.ResUtil;
import com.yoomiito.app.utils.RouterUtils;
import com.yoomiito.app.utils.Type;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.utils.wx.UMengShareUtils;
import com.yoomiito.app.widget.dialog.CameraDialog;
import com.yoomiito.app.widget.dialog.ShareBottomDialog_1;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.router.Router;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import kotlin.Unit;

public class WebViewActivity extends BaseActivity<WebViewPresenter> {

    @BindView(R.id.act_webView)
    WebView mWebView;
    @BindView(R.id.title_bar)
    RelativeLayout parentTitleView;
    @BindView(R.id.tv_center)
    TextView titleTv;
    @BindView(R.id.tv_back_left)
    TextView titleLeft;
    @BindView(R.id.tv_right)
    TextView rightTv;
    @BindView(R.id.free_buy_ll)
    LinearLayout mFreeBuyLl;
    @BindView(R.id.free_buy)
    TextView mBuyTv;
    @BindView(R.id.right_iv)
    ImageView rightIv;
    /**
     * *********************最新
     * 用户协议 => https://r-m.yoomiito.com/app/agreement/index.html
     * 隐私协议 => https://r-m.yoomiito.com/app/privacy/index.html
     * 常见问题 => https://r-m.yoomiito.com/app/faqs/index.html
     * 最新*************
     * <p>
     * ### product - 淘宝商品详情
     * https://h5.yoomiito.com/app/product/index.html?id=[淘宝商品id]&shareUserId=[分享用户id]
     * <p>
     * ### vipproduct - 礼包商品详情
     * https://h5.yoomiito.com/app/vipproduct/index.html?id=[礼包商品id]
     * <p>
     * ### invitation - 分享
     * https://h5.yoomiito.com/app/invitation/index.html?code=[六位邀请码]
     * <p>
     * ### download - 下载页面
     * https://h5.yoomiito.com/app/download/index.html
     * <p>
     * ### video - 视频教程-新手教程
     * https://h5.yoomiito.com/app/video/index.html
     * <p>
     * ### protocol - 用户协议
     * https://h5.yoomiito.com/app/protocol/index.html
     * <p>
     * ### faq - 常见问题
     * https://h5.yoomiito.com/app/faq/index.html
     */


    private String mUrl;
    private int mType = -1;
    private String mInviteCode;
    //**********搜券查佣金**********
//    private GoodsDetail goodsInfo;
//    private String[] goodsDetailUrls = {
//            "https://detail.m.tmall.com/",
//            "https://detail.m.liangxinyao.com",
//            "https://h5.m.taobao.com",
//            "https://detail.m.tmall.hk"};
    //**********搜券查佣金**********
    private static final String CallBack = "call_back";
    private static int REQUEST_SELECT_IMAGES_CODE = 7;//请求选择图片
    private ValueCallback<Uri[]> filePathCallback;
    public List<String> imageBeanList = new ArrayList<>();//相册图片
    public List<String> imagePaths;
    //    protected FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(
//            ViewGroup.LayoutParams.MATCH_PARENT,
//            ViewGroup.LayoutParams.MATCH_PARENT
//    );
    protected FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
    );
    private View customView = null;
    private FrameLayout fullscreenContainer = null;
    private WebChromeClient.CustomViewCallback customViewCallback = null;

    @Override
    public int getLayoutId() {
        return R.layout.act_webview;
    }

    @Override
    public WebViewPresenter newP() {
        return new WebViewPresenter(App.mAppConfig);
    }

    /**
     * 不适用于有邀请码的
     *
     * @param context
     * @param data    6593323275101667330
     * @param type    6593323275101667330
     */
    public static void start(Context context, String data, int type) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(Constant.DATA, data);
        intent.putExtra(Constant.TYPE, type);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void start(Context context, String data) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(Constant.DATA, data);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mUrl = getIntent().getStringExtra(Constant.DATA);
        mType = getIntent().getIntExtra(Constant.TYPE, -1);
        mInviteCode = getIntent().getStringExtra(Constant.INVITE_CODE);
        initWebView();
        initEvent();
        switch (mType) {
            case AllCode.FAQ:
                mUrl = NetUrl.FAQUrl;
//                mUrl = "https://r-m.yoomiito.com/app/test.html";
//                mUrl = "https://m.yoomii00.com/app/mpproduct/?inviter=012466&id=5176366947310161";
                break;
            case AllCode.NewVideo:
                mUrl = NetUrl.VideoUrl;
                break;
            case AllCode.UserAgreement:
                rightTv.setVisibility(View.GONE);
                mUrl = NetUrl.UserAgreementUrl;
                break;
            case Const.Url.PrivacyAgreement:
                rightTv.setVisibility(View.GONE);
                mUrl = NetUrl.PrivacyAgreementUrl;
                break;
            case AllCode.InviteFriend:
                mUrl = NetUrl.InviteFriendUrl + mInviteCode;
                break;
            case AllCode.CustomService:
//                break;
            case AllCode.CustomServiceVIP:
//                mUrl = NetUrl.CustomServiceUrl + "?cid=" + UserInfoConfig.getCompanyId();
                mUrl = NetUrl.CustomServiceUrl;
                break;
            case AllCode.VIPRight:
                mUrl = NetUrl.VIPUrl + UserInfoConfig.getRoleId();
                break;
            case AllCode.AboutUs:
                String versionName = AllUtils.getVersionInfo().versionName;
                mUrl = NetUrl.AboutUs + "?version=" + versionName;
                break;
            case AllCode.BannerType_1:
                titleLeft.setText("关闭");
                titleLeft.setTextColor(ResUtil.getColor(R.color.color_balk_333333));
                titleLeft.setTextSize(16);
                titleLeft.setVisibility(View.VISIBLE);
                titleLeft.getPaint().setFakeBoldText(true);
//                parentTitleView.setVisibility(View.VISIBLE);
//                titleBarParentView_2.setVisibility(View.VISIBLE);
                break;
            case Const.Url.SddVipRights:
                mUrl = NetUrl.SddVipRightUrl;
                break;
            case Const.Url.YiJiaYou:

                break;
            case Const.Url.MeiTuan:
                setCookies(mUrl);
                mFreeBuyLl.setVisibility(View.VISIBLE);
                mBuyTv.setBackground(ColorUtils.INSTANCE.gradientAndRadius("#FFFCBE50", "#FFFDD45D", 25, GradientDrawable.Orientation.LEFT_RIGHT));
                mBuyTv.setText("分享红包");
                break;
            case Const.Url.CreditCard:
                break;
        }
        L.i("加载Url: " + mUrl);
        mWebView.loadUrl(mUrl);
        //搜券查佣金
//        collection.setChangeListener((view, isSelected) -> {
//            if (isSelected) {
//                getP().addCollection(goodsId);
//            } else {
//                getP().delCollection(goodsId);
//            }
//        });
    }


    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings settings = mWebView.getSettings();
        settings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        settings.setDisplayZoomControls(true); //隐藏原生的缩放控件
        settings.setBlockNetworkImage(false);//解决图片不显示
        settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        settings.setJavaScriptEnabled(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setAllowContentAccess(true); // 是否可访问Content Provider的资源，默认值 true
        settings.setAllowFileAccess(true);    // 是否可访问本地文件，默认值 true
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setDefaultTextEncodingName("UTF -8");// 设置默认为utf- 8
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setSupportZoom(true);// 缩放开关
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setTextSize(WebSettings.TextSize.NORMAL);
        settings.setAppCacheEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);//开启DOM缓存
        settings.setSavePassword(true);
        settings.setJavaScriptEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        settings.setTextZoom(100);
        settings.setUseWideViewPort(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
//        settings.setUserAgentString("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
//        clearCookies();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && BuildConfig.DEBUG) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        if (agreed) {
            String userAgentString = settings.getUserAgentString();
            settings.setUserAgentString(userAgentString + " Qiannianai/" + AllUtils.getVersionInfo().versionName);
            //允许webView下载，但是交付给系统浏览器下载
            mWebView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
                L.i("U: " + url + "   ag:" + userAgent + "  cd:" + contentDisposition + "  mi:" + mimetype + "  l:" + contentLength);
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                intent.setData(Uri.parse(url));
                startActivity(intent.createChooser(intent, "请选择浏览器"));
            });
        }

    }

    private String goodsId;

    protected void initEvent() {
        mWebView.addJavascriptInterface(new JSFun(), "appInterface");
        mWebView.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                L.i("拦截URL:" + url);
//                if (url.startsWith("http:") || url.startsWith("https:")) {
//                    return false;
//                }
//                try {
//                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                    startActivity(intent);
//                }catch (Exception e){
//                    return false;
//                }
////  下面这一行保留的时候，原网页仍报错，新网页正常.所以注释掉后，也就没问题了
////          view.loadUrl(url);
//                return true;
//                if (url.contains("ymmt_share=1")){
//                    rightIv.setImageResource(R.drawable.icon_share);
//                    rightIv.setVisibility(View.VISIBLE);
//                    rightIv.setOnClickListener(v -> {
//                        showShareDialog();
//                    });
//                }
                if (!agreed) {
                    return false;
                }
                if (url.startsWith("tel:")) {//da电话
                    DeviceConfigUtils.INSTANCE.inputTelNum(WebViewActivity.this, url);
                    return true;
                } else if (url.startsWith("weixin://wap/pay")
                        || url.startsWith("alipays:")
                        || url.startsWith("alipay")
                        || url.startsWith("imeituan://")
                        || url.startsWith("baidumap:")) {
                    L.i("mType:" + mType + "   " + (mType == Const.Url.YiJiaYou));
                    if (mType == Const.Url.YiJiaYou) {
                        if (url.startsWith("weixin://wap/pay")
                                || url.startsWith("alipays:")
                                || url.startsWith("alipay")) {
                            getP().oilRecord();
                        }
                    }
                    //调起微信 支付宝支付
                    try {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
                        String tip = "";
                        if (url.startsWith("weixin://wap/pay")) {
                            tip = "请下载微信";
                        } else if (url.startsWith("alipays:")) {
                            tip = "请下载支付宝";
                        } else if (url.startsWith("imeituan://")) {
                            tip = "请下载美团";
                        } else if (url.startsWith("baidumap:")) {
                            tip = "请下载百度地图";
                        }
                        if (!TextUtils.isEmpty(tip)) {
                            YMToast.showCenterToast(tip);
                        }
                    }
                    return true;
                }
                //调起支付宝支付
//                boolean isInterceptor = PayTypeUtils.aliH5ToAppPay(WebViewActivity.this, url, returnUrl -> {
//                    if (!TextUtils.isEmpty(returnUrl)) {
//                        mWebView.loadUrl(returnUrl);
//                    }
//                });
//                L.i("是否拦截："+isInterceptor);
//                if (isInterceptor){
//                    return true;
//                }
                if (url.contains("/app/mpproduct")) {
                    String regular = "(?<=(\\?|&)id=).*?(?=&|$)";
                    Pattern pattern = Pattern.compile(regular);
                    Matcher matcher = pattern.matcher(url);
                    if (matcher.find()) {
                        String id = matcher.group();
                        RouterUtils.toGoodsDetail(WebViewActivity.this, id, Type.GoodsType.BaoPin);
                    }
//                    String m = url.substring(url.indexOf("?")+1);
//                    String[] params = m.split("&");
//                    for (String s:params) {
//                        if (s.contains("id=")){
//                            String id = s.substring(s.indexOf("=")+1);
//                            RouterUtils.toGoodsDetail(WebViewActivity.this,id, Type.GoodsType.BaoPin);
//                        }
//                    }
                    return true;
                }
                return false;
            }

            //开始加载
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if (agreed) {
                    if (url.contains("ymmt_share=1")) {
                        rightIv.setImageResource(R.drawable.icon_share);
                        rightIv.setVisibility(View.VISIBLE);
                        rightIv.setOnClickListener(v -> {
                            showShareDialog();
                        });
                    }
                }
//                if (url.contains("404.jsp")) {
//                    mWebView.stopLoading();
//                }
            }

            //加载完毕
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                L.i("加载完成:" + url);
                setTitle(view.getTitle());
//                stateLayout.showContentView();
                //调用html中的app()方法传递一个标识
//                mWebView.post(() -> mWebView.loadUrl("javascript:hiddenHeadAndFoot()"));
//                Observable.fromArray(goodsDetailUrls)
//                        .filter(new Predicate<String>() {
//                            @Override
//                            public boolean test(String s) throws Exception {
//                                return url.contains(s);
//                            }
//                        })
//                        .
                //搜券查佣金
//                if (AllCode.BannerType_1==mType){
//                    for (String u : goodsDetailUrls) {
//                        if (url.contains(u)) {
//                            int position = url.indexOf("?");
//                            String[] params = url.substring(position + 1).split("&");
//                            for (String s : params) {
//                                String[] str = s.split("=");
//                                if (str[0].equals("id")) {
//                                    goodsId = str[1];
//                                    mSearchCouponTv.setVisibility(View.VISIBLE);
//                                    mFreeBuyLl.setVisibility(View.VISIBLE);
//                                    return;
//                                }
//                            }
//                        }
//                    }
//                    mSearchCouponTv.setVisibility(View.GONE);
//                    mSearchCouponTv.setText("点击下方【搜券查佣金】");
//                    mFreeBuyLl.setVisibility(View.GONE);
//                    mBottomBtn.setVisibility(View.GONE);
//                }
            }


            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                if (sslError.getPrimaryError() == android.net.http.SslError.SSL_INVALID) {
                    sslErrorHandler.proceed();
                } else {
                    super.onReceivedSslError(webView, sslErrorHandler, sslError);
//                    sslErrorHandler.cancel();
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                L.i("错了11 " + errorCode + "  " + description + "  " + failingUrl);
                if (errorCode == ERROR_TIMEOUT || errorCode == ERROR_CONNECT) {
//                    showErrorView();
                }
            }

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                L.i("错了00 " + error.getDescription() + "  " + request.getRequestHeaders().toString());

            }


            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                L.i("错了 " + errorResponse.getReasonPhrase() + "  " + request.getRequestHeaders().toString());

            }

        });
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

//            @Override
//            public void onShowCustomView(View view, CustomViewCallback callback) {
//                super.onShowCustomView(view, callback);
//                showCustomView(view, callback);
//            }
//
//            @Override
//            public void onHideCustomView() {
//                super.onHideCustomView();
//                hideCustomView();
//            }

            //加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                L.i("进度：" + newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                setTitle(view.getTitle());
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
//                String[] types = fileChooserParams.getAcceptTypes();//可以区分相机、相册 image/* video/*
                if (agreed) {
                    AllUtils.requestPermission3(WebViewActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                            .subscribe(per -> {
                                if (per.granted) {
                                    WebViewActivity.this.filePathCallback = filePathCallback;
                                    showCameraDialog(filePathCallback);
                                } else if (per.shouldShowRequestPermissionRationale) {
                                    filePathCallback.onReceiveValue(null);
                                } else {
                                    YMToast.showText("请打开您的相册、相机使用权限");
                                    filePathCallback.onReceiveValue(null);
                                }
                            });
                }
                return true;
            }

        });

//        stateLayout.setErrorAction(view -> {
//            stateLayout.showProgressView();
//            switchViewByNetwork();
//        });
    }

    private void setTitle(String title) {
        if (Const.Url.CreditCard == mType) {
            titleTv.setText("智能用卡");
        } else {
            if (title == null) {
                titleTv.setText("");
            } else {
                titleTv.setText(title.startsWith("http") || title.startsWith("https") ? "" : (title.length() > 11 ? (title.subSequence(0, 10) + "...") : title));
            }
        }
    }

    /**
     * 视频播放全屏
     **/
    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }
        WebViewActivity.this.getWindow().getDecorView();
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        fullscreenContainer = new FullscreenHolder(WebViewActivity.this);
        boolean d = ((App.mHeightPx * 9) / (App.mWidthPx * 16)) >= 1;
        FrameLayout.LayoutParams View_COVER_SCREEN_PARAMS;
        if (d) {
            int height = App.mWidthPx > App.mHeightPx ? App.mHeightPx : App.mWidthPx;//取最小
            View_COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(height * 16 / 9, height);
        } else {
            int width = App.mWidthPx > App.mHeightPx ? App.mWidthPx : App.mHeightPx;
            View_COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(width, width * 9 / 16);
        }
        View_COVER_SCREEN_PARAMS.gravity = Gravity.CENTER;
        fullscreenContainer.addView(view, View_COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        mWebView.setVisibility(View.GONE);
        setStatusBarVisibility(false);
        customViewCallback = callback;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    }

    /**
     * 隐藏视频全屏
     */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        mWebView.setVisibility(View.VISIBLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /**
     * 全屏容器界面
     */
    class FullscreenHolder extends FrameLayout {

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            return true;
        }

        public FullscreenHolder(@NonNull Context context) {
            super(context);
            setBackgroundColor(context.getResources().getColor(android.R.color.black));
        }
    }

    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

//    @Override
//    public void onConfigurationChanged(Configuration newConfig) {
//        // TODO Auto-generated method stub
//        super.onConfigurationChanged(newConfig);
//        switch (newConfig.orientation) {
//            case Configuration.ORIENTATION_LANDSCAPE:
//                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
//                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//                break;
//            case Configuration.ORIENTATION_PORTRAIT:
//                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
//                break;
//        }
//
//    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (customView != null) {
                    hideCustomView();
                } else if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }

    private void showShareDialog() {
        ShareBottomDialog_1 shareBottomDialog_1 = new ShareBottomDialog_1(this);
        shareBottomDialog_1.setOnShareItemClickListener(type -> {
            String title = mWebView.getTitle();
            if (type == 1) {
                UMengShareUtils.shareWX(this, title, mUrl, title, R.drawable.app_launcher);
            } else if (type == 2) {
                UMengShareUtils.shareWXCircle(this, title, mUrl, title, R.drawable.app_launcher);
            }
            shareBottomDialog_1.dismiss();
        });
        shareBottomDialog_1.show();
        shareBottomDialog_1.showSavePic(false);
    }

    public boolean netCanUse() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) App.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            if (!mNetworkInfo.isAvailable()) {
                return false;
            }
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                NetworkCapabilities networkCapabilities = mConnectivityManager.getNetworkCapabilities(mConnectivityManager.getActiveNetwork());
                return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
            } else {
                Runtime runtime = Runtime.getRuntime();
                try {
                    Process ipProcess = runtime.exec("ping -c 3 www.baidu.com");
                    int exitValue = ipProcess.waitFor();
                    Log.i("Avalible", "Process:" + exitValue);
                    return (exitValue == 0);
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    public void clearCookies() {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
    }

    @Override
    public void finish() {
        if (mWebView != null)
            mWebView.stopLoading();
        super.finish();
    }

    //R.id.title_left,R.id.back,
    @OnClick({R.id.iv_back_left, R.id.tv_back_left, R.id.free_buy})
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.title_left:
            case R.id.tv_back_left:
                finish();
                break;
            case R.id.iv_back_left:
                if (mWebView != null && mWebView.canGoBack()) {
                    mWebView.goBack();//返回上个页面
                    return;
                } else {
                    finish();
                }
                break;
//            case R.id.back:
//                if (mWebView != null && mWebView.canGoBack()) {
//                    mWebView.goBack();
//                } else {
//                    finish();
//                }
//                break;
            //************搜券查佣金************
            case R.id.free_buy:
                if (mType == Const.Url.MeiTuan) {
                    List<String> sd = new ArrayList();
                    sd.add(mUrl);
                    ShareActivity.Companion.start(this, new ShareViewData(sd));
                }
//                else {
//                    if (TextUtils.isEmpty(UserInfoConfig.getRelationId())) {
//                        RouterUtils.getTBAuthorization(this);
//                    } else {
//                        getP().getGoodsInfo(goodsId, "1");
//                    }
//                }

                break;
//            case R.id.item_bottom_btn_left:
//                RouterUtils.toShareGoods(WebViewActivity.this, goodsId, AllCode.TaoBao);
//                break;
//            case R.id.item_bottom_btn_right:
//                if (SpannableUtils.isEmptyOr0(goodsInfo.getCoupon_price())) {//立即购买
//                    RouterUtils.TaoBaoWithUrl(goodsInfo.getItem_url());
//                } else {
//                    RouterUtils.TaoBaoWithUrl(goodsInfo.getCoupon_click_url());
//                }
//                break;
            //**********搜券查佣金**********
        }
    }

    //**********搜券查佣金**********
//    public void setGoodsInfo(GoodsDetail goodsInfo) {
//        if (goodsInfo != null) {
//            this.goodsInfo = goodsInfo;
//            mBottomBtn.setVisibility(View.VISIBLE);
//            mFreeBuyLl.setVisibility(View.GONE);
//            collection.setSelect(goodsInfo.getIs_collection() == 1 ? true : false);
//            if (UserInfoConfig.getRoleId() > LevelType.VIP_0) {
//                if (SpannableUtils.isEmptyOr0(goodsInfo.getGet_money())) {
//                    shareBtnTv.setText("立即购买");
//                    mShareFanYongTv.setVisibility(View.GONE);
//                    mShareLingQuanTv.setVisibility(View.GONE);
//                } else {
//                    mSearchCouponTv.setText("返佣：¥" + goodsInfo.getGet_money());
//                    mShareFanYongTv.setText("返佣：¥" + goodsInfo.getGet_money());
//                    mShareLingQuanTv.setText("返佣：¥" + goodsInfo.getGet_money());
//                    mShareLingQuanTv.setVisibility(View.VISIBLE);
//                    mShareFanYongTv.setVisibility(View.VISIBLE);
//                }
//            } else {
//                shareFlagTv.setText("分享");
//                if (SpannableUtils.isEmptyOr0(goodsInfo.getGet_money())) {
//                    shareBtnTv.setText("立即购买");
//                } else {
//                    shareBtnTv.setText("领券购买");
//                }
//
//                mShareFanYongTv.setVisibility(View.GONE);
//                mShareLingQuanTv.setVisibility(View.GONE);
//                mSearchCouponTv.setVisibility(View.GONE);
//            }
//        }
//    }
    //**********搜券查佣金**********

    private String callback;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            imagePaths = ImageSelector.getImagePaths(data);
            L.i("选择的图片数量：" + imagePaths.size());
            imageBeanList.clear();
            showLoading();
            getP().uploadPhotos(0);
//            Observable.just(1)
//                    .subscribeOn(AndroidSchedulers.mainThread())
//                    .subscribe(v -> {
//
//                    });
        } else if (requestCode == ImageUtils.REQUEST_CODE_CAMERA && resultCode == RESULT_OK) {
            if (filePathCallback == null) {
                YMToast.showCenterToast("照片上传异常，请重新操作");
                WebViewActivity.this.finish();
                return;
            }
            Uri[] results = new Uri[]{ImageUtils.photoUri};
            filePathCallback.onReceiveValue(results);
            filePathCallback = null;
        } else if (requestCode == ImageUtils.REQUEST_CODE_ALBUM && resultCode == RESULT_OK) {
            if (filePathCallback == null) {
                YMToast.showCenterToast("照片上传异常，请重新操作");
                WebViewActivity.this.finish();
                return;
            }
            Uri[] results = new Uri[]{data.getData()};
            filePathCallback.onReceiveValue(results);
            filePathCallback = null;
        }
        if (resultCode == RESULT_CANCELED) {
            if (filePathCallback == null) {
                YMToast.showCenterToast("出现异常，请重新操作");
                WebViewActivity.this.finish();
                return;
            }
            if (filePathCallback != null) {
                filePathCallback.onReceiveValue(null);
                filePathCallback = null;
            }
        }
//        } else if (requestCode == Constant.CODE_GET_ORDER_INFO_REQUEST_ID && resultCode == Constant.CODE_GET_ORDER_INFO_RESULT_ID) {
//            getP().setProductId(data.getStringExtra(Constant.KEY_PRODUCT_ID));
//            getP().setOrderId(data.getStringExtra(Constant.KEY_ORDER_ID));
//            getP().setGoodsType(data.getIntExtra(Constant.KEY_ORDER_TYPE, 0));
//            String title = data.getStringExtra(Constant.KEY_TITLE);
//            mBuyGoodsIv.setRightText(title);
//            getP().getProductInfoData();
//            checkBtnState();
//        }else if (requestCode == REQUEST_PHOTO_CODE) {
//            if (resultCode==RESULT_OK){
//                List<String> imagePaths = new ArrayList<>();
//                imagePaths.add(getP().getmCurrentPhotoPath());
//                mImagePathList.addAll(imagePaths);
//                addImages(imagePaths, true);
//                checkBtnState();
//            }
//        }
    }

    private void showCameraDialog(ValueCallback<Uri[]> filePathCallback) {
        CameraDialog cameraDialog = new CameraDialog(this, filePathCallback);
        cameraDialog.show();
    }

    public void setCookies(String cookiesPath) {
        Map<String, String> cookieMap = new HashMap<>();
        String cookie = getSharedPreferences("cookie", Context.MODE_PRIVATE).getString("cookies", "");// 从SharedPreferences中获取整个Cookie串
        if (!TextUtils.isEmpty(cookie)) {
            String[] cookieArray = cookie.split(";");// 多个Cookie是使用分号分隔的
            for (int i = 0; i < cookieArray.length; i++) {
                int position = cookieArray[i].indexOf("=");// 在Cookie中键值使用等号分隔
                String cookieName = cookieArray[i].substring(0, position);// 获取键
                String cookieValue = cookieArray[i].substring(position + 1);// 获取值

                String value = cookieName + "=" + cookieValue;// 键值对拼接成 value
                Log.i("cookie", value);
                CookieManager.getInstance().setCookie(getDomain(cookiesPath), value);// 设置 Cookie
            }
        }
    }

    @Override
    protected void onDestroy() {
        mWebView.clearHistory();
        mWebView.clearFormData();
        mWebView.clearCache(true);
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
        CookieManager cookieManager = CookieManager.getInstance();
        String cookieStr = cookieManager.getCookie(getDomain(mUrl));
        SharedPreferences preferences = getSharedPreferences("cookie", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("cookies", cookieStr);
        editor.commit();
    }

    private String getDomain(String url) {
        url = url.replace("http://", "").replace("https://", "");
        if (url.contains("/")) {
            url = url.substring(0, url.indexOf('/'));
        }
        return url;
    }

    public void uploadOk() {
        L.i("上传完成");
        Observable.just(1)
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(c -> {
                    Map<String, List<String>> params = new HashMap();
                    params.put("imgUrls", imageBeanList);
                    String data = JSONObject.toJSONString(params);
                    callback(callback, data);
                    dismissLoading();
                });

    }

//    private AMapLocationListener mLocationListener = new AMapLocationListener() {
//
//        @Override
//        public void onLocationChanged(AMapLocation aMapLocation) {
//            dismissLoading();
//            L.i("定位结果：" + aMapLocation.toString());
//            if (aMapLocation.getErrorCode() == AMapLocation.LOCATION_SUCCESS) {
//                Observable.just(1)
//                        .subscribeOn(AndroidSchedulers.mainThread())
//                        .subscribe(c -> {
//                            Map<String, String> params = new HashMap();
//                            params.put("lat", aMapLocation.getLatitude() + "");
//                            params.put("lng", aMapLocation.getLongitude() + "");
//                            String data = JSONObject.toJSONString(params);
//                            callback(callback, data);
//                            dismissLoading();
//                        });
//            } else {
//                YMToast.showCenterToast("定位失败，请重试");
//            }
//        }
//    };
//    private AMapLocationClient mLocationClient;
//    private AMapLocationClientOption option;

    private void startLocation() {
        L.i("开始定位");
//        if (mLocationClient == null) {
//            mLocationClient = new AMapLocationClient(this);
//            mLocationClient.setLocationListener(mLocationListener);
//            if (option == null) {
//                option = new AMapLocationClientOption();
//                ////LocationMode.Hight_Accuracy：高精度；
//                ////LocationMode. Battery_Saving：低功耗；
//                ////LocationMode. Device_Sensors：仅使用设备；
//                option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
//                option.setOnceLocation(true); //单次定位
//                //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。
//                //如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
//                option.setOnceLocationLatest(true);
//                option.setNeedAddress(true); //是否需要返回地址描述。
//                option.setHttpTimeOut(3000); //定位超时时间
//            }
//            mLocationClient.setLocationOption(option);
//        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            AllUtils.requestPermission3(this, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                    .subscribe(new Consumer<Permission>() {
//                        @Override
//                        public void accept(Permission permission) throws Exception {
//                            if (permission.granted) {
//                                showLoading();
//                                mLocationClient.startLocation();
//                            } else if (permission.shouldShowRequestPermissionRationale) {
//
//                            } else {
//                                YMToast.showCenterToast("请去设置中开启定位权限");
//                            }
//                        }
//                    });
//        } else {
//            showLoading();
//            mLocationClient.startLocation();
//        }
    }

    public class JSFun {

//        @Deprecated
//        @JavascriptInterface
//        public void getApptoken(String result) {
//            Log.i("YOM", "getApptoken:" + result);
//            JSONObject jsonObject = JSONObject.parseObject(result);
//            String callback = jsonObject.getString("callback");
//            String token = App.mAppConfig.getIsLogin()?SharedPref.getInstance(App.getInstance()).getString(Constant.TOKEN, ""):"";
//
//            Message message = mHandler.obtainMessage();
//            Bundle bundle = new Bundle();
//            bundle.putString(CallBack, callback);
//            bundle.putString(Constant.TYPE, "getApptoken");
//            bundle.putString(Constant.TOKEN, token);
//            message.setData(bundle);
//            mHandler.sendMessage(message);
//        }

        @JavascriptInterface
        public void getCurrentPosition(String result) {
            L.i("Result: " + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            callback = jsonObject.getString("callback");
            Observable.just(1)
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .subscribe(c -> {
                        startLocation();
                    });
        }

        @JavascriptInterface
        public void getToken(String result) {
            L.i("getToken:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String callback = jsonObject.getString("callback");
            String token = SharedPref.getInstance(App.getInstance()).getString(Constant.TOKEN, "");

            Message message = mHandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString(CallBack, callback);
            bundle.putString(Constant.TYPE, "getToken");
            bundle.putString(Constant.TOKEN, token);
            message.setData(bundle);
            mHandler.sendMessage(message);
        }


        @Deprecated
        @JavascriptInterface
        public void getUserinfo(String result) {
            Log.i("YOM", "getUserinfoR:" + result);
//            JSONObject jsonObject = JSONObject.parseObject(result);
//            String callback = jsonObject.getString("callback");
//            int data = jsonObject.getIntValue("data");
        }

        @JavascriptInterface
        public void jumpOrder() {
            startActivity(new Intent(WebViewActivity.this, OrderActivity.class));
        }


        @JavascriptInterface
        public void saveImage(String result) {
            Log.i("YOM", "SS：:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String callback = jsonObject.getString("callback");
            String data = jsonObject.getString("data");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Glide.with(context)
                            .asFile()
                            .load(data)
                            .downloadOnly(new SimpleTarget<File>() {
                                @Override
                                public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
                                    FileUtils.INSTANCE.createSaveFile(
                                            context,
                                            resource,
                                            1,
                                            getTempFileName()+".jpg",
                                            "sharePic"
                                    );


                                }
                            });
                }
            });
            Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();

            Message message = mHandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString(CallBack, callback);
            bundle.putString(Constant.TYPE, "saveImage");
            message.setData(bundle);
            mHandler.sendMessage(message);
//            callback(callback);
//            HashMap hashMap = new HashMap();
//            hashMap.put("code", 200);
//            hashMap.put("data", "");
//            String s2 = JSONObject.toJSONString(hashMap);
//            mWebView.loadUrl("javascript:" + callback + "(" + s2 + ")");
        }

        @Deprecated
        @JavascriptInterface
        public void setNavigationTitle(String result) {
            Log.i("YOM", "setNavigationTitle:" + result);
//            JSONObject jsonObject = JSONObject.parseObject(result);
//            String callback = jsonObject.getString("callback");
//            int data = jsonObject.getIntValue("data");
        }

        @JavascriptInterface
        public void setNavigationRight(String result) {
            Log.i("YOM", "setNavigationRight:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String callback = jsonObject.getString("callback");
            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
            String type = jsonObject1.getString("type");// WEBVIEW打开指定web， CALLBACK点击回调
            String text = jsonObject1.getString("text");//显示的文本
            String url = jsonObject1.getString("url");  // 当 type=WEBVIEW 时才有，跳转的url

            switch (type) {
                case "WEBVIEW":
                    Observable
                            .just(url)
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .subscribe(s -> {
                                rightTv.setVisibility(View.VISIBLE);
                                rightTv.setText(text);
                                rightTv.setTextSize(16);
                                rightTv.setTextColor(ResUtil.getColor(R.color.color_text));
                                rightTv.setOnClickListener(v -> {
                                    mWebView.loadUrl(s);
                                    rightTv.setVisibility(View.GONE);
                                });
                            });
                    break;
                case "CALLBACK":
                    mWebView.evaluateJavascript(callback, value -> {
                        //此处为 js 返回的结果

                    });
                    break;
            }
            Message message = mHandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString(CallBack, callback);
            bundle.putString(Constant.TYPE, "setNavigationRight");
            message.setData(bundle);
            mHandler.sendMessage(message);
        }

        @JavascriptInterface
        public void share(String result) {
            L.i("h5分享:  " + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String callback = jsonObject.getString("callback");
            JSONObject data = jsonObject.getJSONObject("data");
            String to = data.getString("to");
            String url = data.getString("url");//分享的URL地址
            String type = data.getString("type");
            String title = data.getString("title");//分享标题
            String image = data.getString("image");//分享图片地址
            String description = data.getString("description");//分享描述
            if ("WECHAT".equals(type)) {
                switch (to) {
                    case "TIMELINE"://朋友圈
                        UMengShareUtils.shareWX(SHARE_MEDIA.WEIXIN_CIRCLE, WebViewActivity.this, description, url, title, image);
                        break;
                    case "APPMESSAGE"://好友
                        UMengShareUtils.shareWX(SHARE_MEDIA.WEIXIN, WebViewActivity.this, description, url, title, image);
                        break;
                }
            }
            Message message = mHandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString(CallBack, callback);
            bundle.putString(Constant.TYPE, "share");
            message.setData(bundle);
            mHandler.sendMessage(message);
        }

        @JavascriptInterface
        public void navigate(String result) {
            L.i("navigateR:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String callback = jsonObject.getString("callback");
            String data = jsonObject.getString("data");
            BannerAndIconInfo info = JSONObject.parseObject(data, BannerAndIconInfo.class);
            ActTypeUtils.INSTANCE.handleActFromType(WebViewActivity.this, info);

            Message message = mHandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString(CallBack, callback);
            bundle.putString(Constant.TYPE, "navigate");
            message.setData(bundle);
            mHandler.sendMessage(message);
        }

        @JavascriptInterface
        public void navigateTo(String result) {
//            Log.i("YOM", "navigateToR:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String callback = jsonObject.getString("callback");
            JSONObject data = jsonObject.getJSONObject("data");
            String type = data.getString("type");
            String id = data.getString("id");
            String url = data.getString("url");

            //回调
            Message message = mHandler.obtainMessage();
            if ("WEBVIEW".equals(type)) {
//                Bundle bundle = new Bundle();
//                bundle.putString("Url", url);
//                bundle.putString(Constant.KEY, Constant.INVITE_CODE);
//                message.setInviteFriendData(bundle);

            } else if ("PRODUCT".equals(type)) {//淘宝/天猫商品
                RouterUtils.toGoodsDetail(WebViewActivity.this, id, AllCode.TaoBao);
            } else if ("VIPPRODUCT".equals(type)) {//礼包商品
                RouterUtils.toGoodsDetail(WebViewActivity.this, id, AllCode.Gift);
            } else if ("INVITATION".equals(type)) {//邀请好友
                NewInviteShareActivity.start(WebViewActivity.this, AllCode.InviteFriend);
            }
            Bundle bundle = new Bundle();
            bundle.putString(CallBack, callback);
            bundle.putString(Constant.TYPE, "navigateTo");
            message.setData(bundle);
            mHandler.sendMessage(message);
        }

        @Deprecated
        @JavascriptInterface
        public void upload(String result) {
            Log.i("YOM", "uploadR:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            callback = jsonObject.getString("callback");
            JSONObject data = jsonObject.getJSONObject("data");
            int size = data.getIntValue("max");
//            AllUtils.requestPermission(WebViewActivity.this,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.READ_EXTERNAL_STORAGE)
//                    .subscribe(aBoolean -> {
//                                if (aBoolean) {
            ImageSelector.show(context, REQUEST_SELECT_IMAGES_CODE, size);
//                                }
//                    });
        }

        //
        @JavascriptInterface
        public void switchTab(String s) {//data: 1  //  0:首页， 1:礼包   2:社区   3:我的
            JSONObject jsonObject = JSONObject.parseObject(s);
            String callback = jsonObject.getString("callback");
            int data = jsonObject.getIntValue("data");
            Router.newIntent(WebViewActivity.this)
                    .to(MainActivity.class)
                    .putInt(Constant.ToFM, data)
                    .launch();

            //回调
            Message message = mHandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString(Constant.TYPE, "switchTab");
            bundle.putString(CallBack, callback);
            message.setData(bundle);
            mHandler.sendMessage(message);
//            mWebView.loadUrl("javascript:" + callback + "(" + s2 + ")");
        }

        @JavascriptInterface
        public void launchApp(String result) {
            Log.i("YOM", "launchApp:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String callback = jsonObject.getString("callback");
            JSONObject data = jsonObject.getJSONObject("data");
            String type = data.getString("type");// [TAOBAO, TMALL, OTHER]
            String auth = data.getString("auth");//['Y', 'N'] // 是不是需要授权(登录+淘宝授权)
            String url = data.getString("url");//跳转链接
            if ("Y".equals(auth)) {
                String replace = data.getString("replace");
                if (!TextUtils.isEmpty(replace)) {
                    String[] keys = replace.split(",");
                    Map<String, String> params = AllUtils.getMemberValue(UserInfoConfig.getUser(), keys);
                    if (null != params) {
                        for (String it : keys) {
                            url = url.replace("{" + it + "}", params.get(it));
                        }
                    }
                }
            }
            switch (type) {
                case "TAOBAO":
                    toTb(auth, url, "taobao");
                    break;
                case "TMALL":
                    toTb(auth, url, "tmall");
                    break;
                case "OTHER":
                    break;
            }
            Message message = mHandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString(CallBack, callback);
            bundle.putString(Constant.TYPE, "launchApp");
            message.setData(bundle);
            mHandler.sendMessage(message);
        }
    }

    private void toTb(String auth, String url, String clientType) {
        if ("Y".equals(auth)) {
            if (!App.mAppConfig.getIsLogin()) {//未登录
//                AllUtils.toLogin(WebViewActivity.this, AllCode.LoginIn);
                LoginUtils.INSTANCE.toOneKeyLogin((BaseActivity) context);
                return;
            }
            if (TextUtils.isEmpty(UserInfoConfig.getRelationId())) {//未授权
                RouterUtils.getTBAuthorization(WebViewActivity.this);
                return;
            }
        }
        RouterUtils.TaoBaoWithUrl(url, clientType);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            if (bundle != null) {
                String type = bundle.getString(Constant.TYPE);
                switch (type) {//不同的method对应不同的处理  default中是通用处理
                    case "getToken":
                        String token = bundle.getString(Constant.TOKEN);
                        callback(bundle.getString(CallBack), token);
                        break;
                    default:
                        callback(bundle.getString(CallBack));
                        String key = bundle.getString(Constant.KEY);
                        if (Constant.INVITE_CODE.equals(key)) {//如果需要跳转到
                            String url = bundle.getString("Url");
                            mWebView.loadUrl(url + UserInfoConfig.getInviteCode());
                        }
                        break;
                }

            }
        }
    };


    private void callback(String callback) {
        HashMap hashMap = new HashMap();
        hashMap.put("code", 200);
        hashMap.put("data", "");
        String s2 = JSONObject.toJSONString(hashMap);
        //4.4以上
//        mWebView.loadUrl("javascript:window." + callback + "(" + s2 + ")");
        mWebView.evaluateJavascript("javascript:window." + callback + "(" + s2 + ")", value -> {
            //此处为 js 返回的结果
        });
    }

    private void callback(String callback, String data) {
        L.i("参数：" + callback + "    " + data);
        HashMap hashMap = new HashMap();
        hashMap.put("code", 200);
        hashMap.put("data", data);
        String s2 = JSONObject.toJSONString(hashMap);
        //4.4以上
//        mWebView.loadUrl("javascript:window." + callback + "(" + s2 + ")");
        mWebView.evaluateJavascript("javascript:window." + callback + "(" + s2 + ")", value -> {
            //此处为 js 返回的结果
        });
    }
}
